import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { io, Socket } from 'socket.io-client';

import '../../Chat.css';
import './GroupChat.css';
import GroupDetails from './GroupDetails';
import PollModal from './PollModal';
import PollMessage from './PollMessage';

import '../../../assets/icons/iconfont.css';
import Icon from '../../Icon';

interface UserData {
  _id?: string; // 用户ID，可选字段
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface Group {
  _id: string;
  name: string;
  members: UserData[];
  admin?: string;
  description?: string;
  qrCode?: string;
  announcement?: string;
  createdBy?: {
    _id: string;
    username: string;
    image: string;
  };
  createdAt?: string;
}

interface GroupMessage {
  _id: string;
  groupId: string;
  from:
    | string
    | {
        _id: string;
        username: string;
        image: string;
      };
  content: string;
  messageType: string;
  time: Date;
  audioData?: string;
  duration?: number;
  videoData?: string;
  systemMessageType?:
    | 'group_name_changed'
    | 'nickname_changed'
    | 'member_joined'
    | 'member_left';
  quote?: {
    sender: string;
    content: string;
  };
  isRecalled?: boolean;
  recalledAt?: Date;
  originalContent?: string;
}

interface GroupChatProps {
  currentUser: UserData;
  selectedGroup: Group;
  onBack: () => void;
  onGroupNameUpdate?: (groupId: string, newName: string) => void;
}

const GroupChat: React.FC<GroupChatProps> = ({
  currentUser,
  selectedGroup,
  onBack,
  onGroupNameUpdate,
}) => {
  const [messages, setMessages] = useState<GroupMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [socket, setSocket] = useState<Socket | null>(null);
  const [typingUsers, setTypingUsers] = useState<string[]>([]);
  const [showGroupDetails, setShowGroupDetails] = useState(false);
  const [groupName, setGroupName] = useState(selectedGroup.name);
  const [groupNicknames, setGroupNicknames] = useState<Record<string, string>>(
    {}
  );
  const [currentGroupMembers, setCurrentGroupMembers] = useState<UserData[]>(
    selectedGroup.members
  );
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [showPlusMenu, setShowPlusMenu] = useState(false);
  const [showPollModal, setShowPollModal] = useState(false);

  // 保存消息到localStorage的通用函数
  const saveMessagesToStorage = (messages: GroupMessage[]) => {
    try {
      localStorage.setItem(
        `groupMessages_${selectedGroup._id}`,
        JSON.stringify(
          messages.map(msg => ({
            ...msg,
            time:
              msg.time instanceof Date
                ? msg.time.toISOString()
                : new Date(msg.time).toISOString(),
          }))
        )
      );
    } catch (error) {
      console.error('保存消息到localStorage失败:', error);
    }
  };

  // 初始化群昵称
  useEffect(() => {
    const loadGroupNicknames = () => {
      const initialNicknames: Record<string, string> = {};
      currentGroupMembers.forEach(member => {
        // 尝试从localStorage加载已保存的昵称
        const savedNickname = localStorage.getItem(
          `groupNickname_${selectedGroup._id}_${member.username}`
        );
        initialNicknames[member.username] = savedNickname || member.username;
      });
      setGroupNicknames(initialNicknames);
    };

    loadGroupNicknames();
  }, [currentGroupMembers, selectedGroup._id]);

  // 监听localStorage变化，同步群昵称
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key && e.key.startsWith(`groupNickname_${selectedGroup._id}_`)) {
        // 重新加载群昵称
        const initialNicknames: Record<string, string> = {};
        currentGroupMembers.forEach(member => {
          const savedNickname = localStorage.getItem(
            `groupNickname_${selectedGroup._id}_${member.username}`
          );
          initialNicknames[member.username] = savedNickname || member.username;
        });
        setGroupNicknames(initialNicknames);
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [currentGroupMembers, selectedGroup._id]);

  // 初始化Socket连接
  useEffect(() => {
    let newSocket: Socket;

    const connectSocket = () => {
      try {
        newSocket = io('http://localhost:3001', {
          transports: ['websocket', 'polling'],
          timeout: 20000,
          reconnection: true,
          reconnectionAttempts: 5,
          reconnectionDelay: 1000,
          forceNew: false,
        });

        setSocket(newSocket);

        // 连接成功
        newSocket.on('connect', () => {
          console.warn('GroupChat Socket连接成功，ID:', newSocket.id);
          // 用户登录到Socket
          newSocket.emit('user_login', currentUser.username);
          // 加入群聊房间
          newSocket.emit('join_group', selectedGroup._id);
        });

        // 监听接收群聊消息（只处理其他用户发送的消息）
        newSocket.on('receive_group_message', (message: GroupMessage) => {
          console.warn('收到群聊消息:', message);
          if (message.groupId === selectedGroup._id) {
            setMessages(prev => {
              // 检查是否已存在相同消息
              const isDuplicate = prev.some(
                existing =>
                  existing.content === message.content &&
                  existing.from === message.from &&
                  Math.abs(
                    new Date(existing.time).getTime() -
                      new Date(message.time).getTime()
                  ) < 2000
              );

              if (isDuplicate) {
                console.warn('检测到重复消息，跳过添加:', message);
                return prev;
              }

              console.warn('添加新消息到列表:', message);
              return [...prev, message];
            });
          }
        });

        // 监听投票更新
        newSocket.on(
          'poll_vote_updated',
          (data: { messageId: string; updatedMessage: GroupMessage }) => {
            console.warn('收到投票更新:', data);
            if (data.messageId) {
              setMessages(prev =>
                prev.map(msg =>
                  msg._id === data.messageId ? data.updatedMessage : msg
                )
              );
            }
          }
        );

        // 监听群名称修改事件
        newSocket.on(
          'group_name_changed',
          (data: {
            groupId: string;
            newName: string;
            oldName: string;
            changedBy: string;
          }) => {
            console.warn('收到群名称修改通知:', data);

            if (data.groupId === selectedGroup._id) {
              // 更新群名称
              setGroupName(data.newName);

              // 创建系统消息
              const systemMessage: GroupMessage = {
                _id: Date.now().toString(),
                groupId: data.groupId,
                from: 'system',
                content: `${data.changedBy}修改了群名称为"${data.newName}"`,
                messageType: 'system',
                time: new Date(),
                systemMessageType: 'group_name_changed',
              };

              // 添加到消息列表
              setMessages(prev => {
                const newMessages = [...prev, systemMessage];
                saveMessagesToStorage(newMessages);
                return newMessages;
              });
            }
          }
        );

        // 监听群昵称修改事件
        newSocket.on(
          'nickname_changed',
          (data: {
            groupId: string;
            newNickname: string;
            oldNickname: string;
            changedBy: string;
          }) => {
            console.warn('收到昵称修改通知:', data);

            if (data.groupId === selectedGroup._id) {
              // 保存群昵称到localStorage
              localStorage.setItem(
                `groupNickname_${data.groupId}_${data.changedBy}`,
                data.newNickname
              );

              // 更新群昵称状态
              setGroupNicknames(prev => ({
                ...prev,
                [data.changedBy]: data.newNickname,
              }));

              // 创建系统消息
              const systemMessage: GroupMessage = {
                _id: Date.now().toString(),
                groupId: data.groupId,
                from: 'system',
                content: `${data.oldNickname}修改了群昵称为"${data.newNickname}"`,
                messageType: 'system',
                time: new Date(),
                systemMessageType: 'nickname_changed',
              };

              // 添加到消息列表
              setMessages(prev => {
                const newMessages = [...prev, systemMessage];
                saveMessagesToStorage(newMessages);
                return newMessages;
              });
            }
          }
        );

        // 监听群聊输入状态
        newSocket.on(
          'group_typing',
          (data: { groupId: string; username: string }) => {
            if (
              data.groupId === selectedGroup._id &&
              data.username !== currentUser.username
            ) {
              setTypingUsers(prev => {
                if (!prev.includes(data.username)) {
                  return [...prev, data.username];
                }
                return prev;
              });
            }
          }
        );

        newSocket.on(
          'group_stop_typing',
          (data: { groupId: string; username: string }) => {
            if (data.groupId === selectedGroup._id) {
              setTypingUsers(prev =>
                prev.filter(user => user !== data.username)
              );
            }
          }
        );

        // 监听群聊消息被撤回
        newSocket.on(
          'group_message_recalled',
          (data: {
            messageId: string;
            from: string;
            groupId: string;
            recalledAt: Date;
          }) => {
            console.warn('收到群聊消息撤回通知:', data);

            if (data.groupId === selectedGroup._id) {
              setMessages(prev =>
                prev.map(msg =>
                  msg._id === data.messageId
                    ? {
                        ...msg,
                        isRecalled: true,
                        recalledAt: data.recalledAt,
                        originalContent: msg.content,
                        content: '此消息已被撤回',
                      }
                    : msg
                )
              );
            }
          }
        );

        // 监听撤回群聊消息成功确认
        newSocket.on(
          'group_message_recall_success',
          (data: {
            messageId: string;
            from: string;
            groupId: string;
            recalledAt: Date;
          }) => {
            console.warn('群聊消息撤回成功:', data);
          }
        );

        // 监听连接错误
        newSocket.on('connect_error', error => {
          console.error('Socket连接错误:', error);
        });

        // 监听断开连接
        newSocket.on('disconnect', reason => {
          console.warn('Socket断开连接:', reason);
        });
      } catch (error) {
        console.error('Socket连接失败:', error);
      }
    };

    connectSocket();

    // 清理函数
    return () => {
      if (newSocket) {
        newSocket.disconnect();
      }
    };
  }, [currentUser.username, selectedGroup._id]);

  // 获取群聊消息历史
  useEffect(() => {
    const fetchGroupMessages = async () => {
      try {
        setLoading(true);

        // 先从localStorage加载消息
        const savedMessages = localStorage.getItem(
          `groupMessages_${selectedGroup._id}`
        );
        if (savedMessages) {
          try {
            const parsedMessages = JSON.parse(savedMessages).map(
              (msg: any) => ({
                ...msg,
                time: new Date(msg.time),
              })
            );
            setMessages(parsedMessages);
            console.warn('从localStorage加载群聊消息:', parsedMessages);
          } catch (e) {
            console.error('解析localStorage消息失败:', e);
          }
        }

        // 然后从服务器获取最新消息
        const response = await axios.get(
          `http://localhost:3001/ysx/groupMessages/${selectedGroup._id}?page=1&limit=50`
        );

        if (response.data.messages) {
          const messagesData = response.data.messages;
          console.warn('获取到群聊消息:', messagesData);
          setMessages(messagesData);
          // 保存到localStorage
          saveMessagesToStorage(messagesData);
        } else {
          console.warn('无法获取有效的群聊消息数据:', response.data);
        }
      } catch (error) {
        console.error('获取群聊消息失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (selectedGroup._id) {
      fetchGroupMessages();
    }
  }, [selectedGroup._id]);

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 发送消息
  const sendMessage = async (content: string, messageType: string = 'text') => {
    if (!content.trim() || !socket) return;

    try {
      const messageData = {
        groupId: selectedGroup._id,
        from: currentUser.username,
        content: content.trim(),
        messageType,
      };

      console.warn('发送群聊消息:', messageData);
      console.warn('当前Socket ID:', socket.id);
      console.warn('当前消息列表长度:', messages.length);

      const response = await axios.post(
        'http://localhost:3001/ysx/groupMessages',
        messageData
      );

      if (response.status === 201) {
        // 消息发送成功，通过Socket广播给其他用户
        console.warn('消息发送成功，通过Socket广播:', messageData);
        socket.emit('send_group_message', messageData);
        setNewMessage('');

        // 将新消息添加到本地消息列表（只添加一次）
        const newMessageObj = response.data;
        console.warn('新消息对象:', newMessageObj);
        setMessages(prev => {
          // 使用更严格的去重逻辑
          const isDuplicate = prev.some(
            existing =>
              existing.content === newMessageObj.content &&
              existing.from === newMessageObj.from &&
              Math.abs(
                new Date(existing.time).getTime() -
                  new Date(newMessageObj.time).getTime()
              ) < 2000 // 2秒内的消息认为是重复的
          );

          if (isDuplicate) {
            console.warn('检测到重复消息，跳过添加:', newMessageObj);
            return prev;
          }

          console.warn('添加本地消息到列表:', newMessageObj);
          return [...prev, newMessageObj];
        });
      }
    } catch (error) {
      console.error('发送群聊消息失败:', error);
    }
  };

  // 处理发送按钮点击
  const handleSend = () => {
    if (newMessage.trim()) {
      sendMessage(newMessage.trim());
    }
  };

  // 创建投票
  const createPoll = async (pollData: any) => {
    try {
      const pollRequestData = {
        groupId: selectedGroup._id,
        from: currentUser.username,
        question: pollData.question,
        options: pollData.options,
        allowMultiple: pollData.allowMultiple,
        expiresAt: pollData.expiresAt,
      };

      const response = await axios.post(
        'http://localhost:3001/ysx/polls',
        pollRequestData
      );

      if (response.status === 201) {
        // 投票创建成功，通过Socket广播给其他用户
        const newPollMessage = response.data;
        const socketMessageData = {
          _id: newPollMessage._id, // 使用真实的ObjectId
          groupId: selectedGroup._id,
          from: currentUser.username,
          content: `投票：${pollData.question}`,
          messageType: 'poll',
          pollData: {
            question: pollData.question,
            options: pollData.options.map((option: string) => ({
              text: option,
              votes: [],
            })),
            allowMultiple: pollData.allowMultiple,
            expiresAt: pollData.expiresAt,
            isExpired: false,
          },
        };
        socket?.emit('send_group_message', socketMessageData);

        // 将新投票添加到本地消息列表
        setMessages(prev => [...prev, newPollMessage]);
      }
    } catch (error) {
      console.error('创建投票失败:', error);
      alert('创建投票失败，请重试');
    }
  };

  // 投票
  const handleVote = async (messageId: string, optionIndex: number) => {
    try {
      const response = await axios.post(
        `http://localhost:3001/ysx/polls/${messageId}/vote`,
        {
          userId: currentUser._id || currentUser.username,
          optionIndex: optionIndex,
        }
      );

      if (response.status === 200) {
        // 投票成功，更新本地消息
        const updatedMessage = response.data;
        setMessages(prev =>
          prev.map(msg => (msg._id === messageId ? updatedMessage : msg))
        );

        // 通过Socket通知群聊中的所有成员投票更新
        if (socket) {
          socket.emit('poll_vote_update', {
            messageId: messageId,
            groupId: selectedGroup._id,
            updatedMessage: updatedMessage,
          });
        }
      }
    } catch (error: any) {
      console.error('投票失败:', error);
      if (error.response?.data?.msg) {
        alert(error.response.data.msg);
      } else {
        alert('投票失败，请重试');
      }
    }
  };

  // 撤回群聊消息
  const recallGroupMessage = async (messageId: string) => {
    try {
      const response = await axios.put(
        'http://localhost:3001/ysx/groupMessages/recall',
        {
          messageId,
          from: currentUser.username,
        }
      );

      if (response.data.msg === '消息撤回成功') {
        // 更新本地消息状态
        setMessages(prev =>
          prev.map(msg =>
            msg._id === messageId
              ? {
                  ...msg,
                  isRecalled: true,
                  recalledAt: new Date(),
                  originalContent: msg.content,
                  content: '此消息已被撤回',
                }
              : msg
          )
        );

        // 通过Socket通知群聊中的所有成员
        if (socket) {
          socket.emit('recall_group_message', {
            messageId,
            from: currentUser.username,
            groupId: selectedGroup._id,
          });
        }
      } else {
        alert(response.data.msg || '撤回失败');
      }
    } catch (error) {
      console.error('撤回群聊消息失败:', error);
      alert('撤回消息失败，请重试');
    }
  };

  // 重新编辑消息
  const reEditGroupMessage = (originalContent: string) => {
    setNewMessage(originalContent);
    // 聚焦到输入框
    const inputElement = document.querySelector(
      '.input-field'
    ) as HTMLInputElement;
    if (inputElement) {
      inputElement.focus();
    }
  };

  // 处理群名称修改
  const handleGroupNameChange = async (
    groupId: string,
    newName: string,
    oldName: string
  ) => {
    try {
      // 调用API修改群名称
      const response = await axios.put(
        `http://localhost:3001/ysx/groups/${groupId}/name`,
        {
          name: newName,
          operatorId: currentUser._id || currentUser.username,
        }
      );

      if (response.data.success) {
        // 更新本地状态
        setGroupName(newName);

        // 通知父组件更新群聊列表
        if (onGroupNameUpdate) {
          onGroupNameUpdate(groupId, newName);
        }

        // 通过Socket通知所有用户（包括自己）
        if (socket) {
          socket.emit('group_name_changed', {
            groupId: groupId,
            newName: newName,
            oldName: oldName,
            changedBy: currentUser.username,
          });
        }

        console.log('群名称修改成功:', newName);
      } else {
        console.error('群名称修改失败:', response.data.message);
        alert('群名称修改失败: ' + response.data.message);
      }
    } catch (error) {
      console.error('群名称修改失败:', error);
      alert('群名称修改失败，请重试');
    }
  };

  // 处理昵称修改
  const handleNicknameChange = (
    groupId: string,
    newNickname: string,
    oldNickname: string
  ) => {
    // 更新群昵称状态
    setGroupNicknames(prev => ({
      ...prev,
      [currentUser.username]: newNickname,
    }));

    // 创建系统消息
    const systemMessage: GroupMessage = {
      _id: Date.now().toString(),
      groupId: groupId,
      from: 'system',
      content: `${oldNickname}修改了群昵称为"${newNickname}"`,
      messageType: 'system',
      time: new Date(),
      systemMessageType: 'nickname_changed',
    };

    // 添加到消息列表
    setMessages(prev => {
      const newMessages = [...prev, systemMessage];
      saveMessagesToStorage(newMessages);
      return newMessages;
    });

    // 通过Socket通知其他用户
    if (socket) {
      socket.emit('nickname_changed', {
        groupId: groupId,
        newNickname: newNickname,
        oldNickname: oldNickname,
        changedBy: currentUser.username,
      });
    }
  };

  // 处理群成员变化（添加或移除）
  const handleMemberAdded = (_groupId: string, newMembers: UserData[]) => {
    console.log('群成员已更新:', newMembers);
    setCurrentGroupMembers(newMembers);

    // 更新群昵称状态，为新成员添加默认昵称
    setGroupNicknames(prev => {
      const updated = { ...prev };
      newMembers.forEach(member => {
        if (!updated[member.username]) {
          updated[member.username] = member.username;
        }
      });
      return updated;
    });
  };

  // 处理回车键
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  // 处理输入状态变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setNewMessage(value);

    // 发送正在输入状态
    if (socket && value.trim()) {
      socket.emit('group_typing', { groupId: selectedGroup._id });
    } else if (socket && !value.trim()) {
      socket.emit('group_stop_typing', { groupId: selectedGroup._id });
    }
  };

  // 处理图片上传
  const handleImageUpload = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB');
      return;
    }

    try {
      // 创建FormData用于上传
      const formData = new FormData();
      formData.append('image', file);

      // 使用图片上传接口
      const uploadResponse = await axios.post(
        'http://localhost:3001/ysx/chat/image/upload',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );

      // 处理上传结果
      if (uploadResponse.data.code === 0) {
        // 上传成功，获取图片URL
        const imageUrl = `http://localhost:3001${uploadResponse.data.data.imageUrl}`;

        // 发送图片消息
        await sendMessage(imageUrl, 'image');

        // 关闭加号菜单
        setShowPlusMenu(false);
      } else {
        // 上传失败
        alert('图片上传失败：' + uploadResponse.data.msg);
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      alert('图片上传失败，请重试');
    }
  };

  // 格式化时间显示
  const formatTime = (date: Date | string) => {
    return new Date(date).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    });
  };
  // 渲染消息
  const renderMessage = (message: GroupMessage, index: number) => {
    // 处理系统消息
    if (message.messageType === 'system') {
      return (
        <React.Fragment key={message._id}>
          {/* 时间分隔符 - 两分钟内只显示第一条消息的时间 */}
          {index > 0 &&
            (() => {
              const currentTime = new Date(message.time);
              const prevTime = new Date(messages[index - 1].time);
              const timeDiff = currentTime.getTime() - prevTime.getTime();
              const minutesDiff = timeDiff / (1000 * 60);

              if (minutesDiff > 2) {
                return (
                  <div className="time-separator">
                    <span>{formatTime(currentTime)}</span>
                  </div>
                );
              }
              return null;
            })()}

          <div className="system-message">
            <span className="system-message-text">{message.content}</span>
          </div>
        </React.Fragment>
      );
    }

    // 处理投票消息
    if (message.messageType === 'poll') {
      return (
        <React.Fragment key={message._id}>
          {/* 时间分隔符 - 两分钟内只显示第一条消息的时间 */}
          {index > 0 &&
            (() => {
              const currentTime = new Date(message.time);
              const prevTime = new Date(messages[index - 1].time);
              const timeDiff = currentTime.getTime() - prevTime.getTime();
              const minutesDiff = timeDiff / (1000 * 60);

              if (minutesDiff > 2) {
                return (
                  <div className="time-separator">
                    <span>{formatTime(currentTime)}</span>
                  </div>
                );
              }
              return null;
            })()}

          <PollMessage
            message={message}
            currentUserId={currentUser._id || currentUser.username}
            onVote={handleVote}
          />
        </React.Fragment>
      );
    }

    // 处理普通消息
    const senderName =
      typeof message.from === 'string'
        ? message.from
        : message.from?.username || '未知用户';
    const isOwnMessage = senderName === currentUser.username;

    // 使用群昵称状态来获取显示名称
    const displayName = groupNicknames[senderName] || senderName;

    return (
      <React.Fragment key={message._id}>
        {/* 时间分隔符 - 两分钟内只显示第一条消息的时间 */}
        {index > 0 &&
          (() => {
            const currentTime = new Date(message.time);
            const prevTime = new Date(messages[index - 1].time);
            const timeDiff = currentTime.getTime() - prevTime.getTime();
            const minutesDiff = timeDiff / (1000 * 60);

            if (minutesDiff > 2) {
              return (
                <div className="time-separator">
                  <span>{formatTime(currentTime)}</span>
                </div>
              );
            }
            return null;
          })()}

        {/* 撤回消息显示 - 像时间分隔符一样居中显示 */}
        {message.isRecalled && (
          <div className="time-separator">
            <span className="recall-text">
              {isOwnMessage
                ? '你撤回了一条消息'
                : `${displayName}撤回了一条消息`}
            </span>
            {isOwnMessage && message.originalContent && (
              <button
                className="re-edit-btn"
                onClick={() => reEditGroupMessage(message.originalContent!)}
              >
                重新编辑
              </button>
            )}
          </div>
        )}

        {/* 撤回的消息不显示气泡 */}
        {!message.isRecalled && (
          <div className={`message ${isOwnMessage ? 'sent' : 'received'}`}>
            <div className="message-content">
              {
                <>
                  {message.messageType === 'text' && (
                    <p className="message-text">{message.content}</p>
                  )}
                  {message.messageType === 'image' && (
                    <div className="image-message">
                      <img
                        src={message.content}
                        alt="群聊图片"
                        className="chat-image"
                        onClick={() => window.open(message.content, '_blank')}
                      />
                    </div>
                  )}
                  {message.messageType === 'voice' && (
                    <div className="voice-message">
                      <button
                        className="voice-play-btn"
                        onClick={() => {
                          // 播放语音的逻辑
                          console.warn('播放语音:', message.content);
                        }}
                      >
                        🔊 {message.duration || 0}s
                      </button>
                    </div>
                  )}
                </>
              }
            </div>

            {/* 撤回按钮 - 只在自己的消息上显示，且未撤回，且发送时间在2分钟内，且是真实的消息ID */}
            {isOwnMessage &&
              !message.isRecalled &&
              (() => {
                // 检查是否是真实的消息ID（ObjectId格式，24位十六进制字符串）
                const isRealMessageId = /^[0-9a-fA-F]{24}$/.test(message._id);

                if (!isRealMessageId) {
                  console.warn('跳过临时群聊消息的撤回按钮:', message._id);
                  return null;
                }

                const now = new Date();
                const messageTime = new Date(message.time);
                const timeDiff = now.getTime() - messageTime.getTime();
                const twoMinutes = 2 * 60 * 1000; // 2分钟的毫秒数

                return timeDiff <= twoMinutes ? (
                  <div className="message-actions">
                    <button
                      className="recall-btn"
                      onClick={() => recallGroupMessage(message._id)}
                      title="撤回消息"
                    >
                      撤回
                    </button>
                  </div>
                ) : null;
              })()}

            <div className="message-info">
              <span className="sender-name">{displayName}</span>
            </div>
          </div>
        )}
      </React.Fragment>
    );
  };

  // 如果显示群详情页面
  if (showGroupDetails) {
    return (
      <GroupDetails
        currentUser={currentUser}
        selectedGroup={{ ...selectedGroup, members: currentGroupMembers }}
        onBack={() => setShowGroupDetails(false)}
        onGroupNameChange={handleGroupNameChange}
        onNicknameChange={handleNicknameChange}
        onMemberAdded={handleMemberAdded}
        groupNicknames={groupNicknames}
      />
    );
  }

  // 切换加号菜单
  const togglePlusMenu = () => {
    setShowPlusMenu(!showPlusMenu);
  };

  if (loading) {
    return (
      <div className="dhat-container">
        <div className="dhat-header">
          <button className="back-btn" onClick={onBack}>
            <Icon iconClass="icon-zuojiantou" size={24} />
          </button>
          <div className="user-info">
            <span className="username">{selectedGroup.name}</span>
            <span className="group-info">
              群聊 ({currentGroupMembers.length}人)
            </span>
          </div>
        </div>
        <div className="loading">加载中...</div>
      </div>
    );
  }

  return (
    <div className="dhat-container">
      {/* 头部 */}
      <div className="dhat-header">
        <button className="back-btn" onClick={onBack}>
          <Icon iconClass="icon-zuojiantou" size={24} />
        </button>
        <div className="user-info">
          <div className="username">{groupName}</div>
          {typingUsers.length > 0 && (
            <div className="typing-indicator">
              {typingUsers.join(', ')} 正在输入...
            </div>
          )}
        </div>
        {/* 右上角三个点按钮 */}
        <button
          className="three-dots-btn"
          title="查看群成员"
          onClick={() => setShowGroupDetails(true)}
        >
          ⋯
        </button>
      </div>

      {/* 消息列表 */}
      <div className="chat-messages">
        {messages.length === 0 ? (
          <div className="no-messages">暂无消息</div>
        ) : (
          <>
            {/* 第一条消息的时间 */}
            <div className="time-separator">
              <span>{formatTime(messages[0].time)}</span>
            </div>

            {/* 渲染消息和时间分隔符 */}
            {messages.map((message, index) => renderMessage(message, index))}
          </>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="message-input">
        <div className="input-container">
          <input
            type="text"
            value={newMessage}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            placeholder="输入消息..."
            className="input-field"
          />
          <div className="button-container">
            {/* 加号按钮 */}
            <div className="button-container" style={{ position: 'relative' }}>
              <div>
                <span onClick={togglePlusMenu}>
                  <Icon iconClass="icon-jiahao" size={24} />
                </span>
              </div>

              {/* 加号功能菜单 */}
              {showPlusMenu && (
                <div className="plus-menu">
                  <div
                    className="menu-item"
                    onClick={() => {
                      document.getElementById('image-upload')?.click();
                      setShowPlusMenu(false);
                    }}
                  >
                    <span className="menu-icon">
                      <Icon iconClass="icon-xiangji1" size={24} />
                    </span>
                    <span className="menu-text">图片</span>
                  </div>
                  <div
                    className="menu-item"
                    onClick={() =>
                      document.getElementById('file-upload')?.click()
                    }
                  >
                    <span className="menu-icon">
                      <Icon iconClass="icon-kaiwenjianjia" size={24} />
                    </span>
                    <span className="menu-text">文件</span>
                  </div>
                  <div
                    className="menu-item"
                    // onClick={() => setShowCamera(true)}
                  >
                    <span className="menu-icon">
                      <Icon
                        iconClass="icon-shipintonghua-tianchong"
                        size={24}
                      />
                    </span>
                    <span className="menu-text">拍摄</span>
                  </div>
                  <div
                    className="menu-item"
                    // onClick={() => setShowLocationPicker(true)}
                  >
                    <span className="menu-icon">
                      <Icon iconClass="icon-position" size={24} />
                    </span>
                    <span className="menu-text">位置</span>
                  </div>
                  <div
                    className="menu-item"
                    // onClick={handleVoiceInput}
                  >
                    <span className="menu-icon">
                      <Icon iconClass="icon-maikefeng" size={24} />
                    </span>
                    <span className="menu-text">
                      {/* {isVoiceInputting ? '停止录音' : '语音转文字'} */}
                    </span>
                  </div>
                  <div className="menu-item">
                    <span className="menu-icon">
                      <Icon iconClass="icon-yuyintonghua" size={24} />
                    </span>
                    <span className="menu-text">语音通话</span>
                  </div>
                  <div className="menu-item">
                    <span className="menu-icon">
                      <Icon
                        iconClass="icon-shipintonghua-tianchong"
                        size={24}
                      />
                    </span>
                    <span className="menu-text">视频通话</span>
                  </div>
                  <div
                    className="menu-item"
                    onClick={() => {
                      setShowPollModal(true);
                      setShowPlusMenu(false);
                    }}
                  >
                    <span className="menu-icon">
                      <Icon iconClass="icon-toupiao" size={24} />
                    </span>
                    <span className="menu-text">投票</span>
                  </div>

                  {/* 隐藏的文件输入 */}
                  <input
                    id="image-upload"
                    type="file"
                    accept="image/*"
                    onChange={handleImageUpload}
                    style={{ display: 'none' }}
                  />
                  <input
                    id="file-upload"
                    type="file"
                    // onChange={handleFileUpload}
                    style={{ display: 'none' }}
                  />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 群成员弹窗 */}
      {showMembersModal && (
        <div
          className="members-modal-overlay"
          onClick={() => setShowMembersModal(false)}
        >
          <div className="members-modal" onClick={e => e.stopPropagation()}>
            <div className="members-modal-header">
              <h3>群成员 ({selectedGroup.members.length}人)</h3>
              <button
                className="close-btn"
                onClick={() => setShowMembersModal(false)}
              >
                ×
              </button>
            </div>
            <div className="members-list">
              {selectedGroup.members.map(member => (
                <div key={member._id} className="member-item">
                  <div className="member-avatar">
                    {member.image ? (
                      <img src={member.image} alt={member.username} />
                    ) : (
                      <div className="default-avatar">
                        {member.username.charAt(0).toUpperCase()}
                      </div>
                    )}
                  </div>
                  <div className="member-info">
                    <span className="member-name">{member.username}</span>
                    {member._id === selectedGroup.createdBy._id && (
                      <span className="member-role">群主</span>
                    )}
                  </div>
                  {/* 只有群主可以看到移除按钮，且不能移除自己 */}
                  {(currentUser._id === selectedGroup.createdBy._id ||
                    currentUser.username ===
                      selectedGroup.createdBy.username) &&
                    member.username !== currentUser.username && (
                      <button
                        className="remove-member-btn"
                        onClick={() =>
                          removeMember(member._id, member.username)
                        }
                        disabled={removingMember === member._id}
                        title="移除成员"
                      >
                        {removingMember === member._id ? '移除中...' : '移除'}
                      </button>
                    )}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
      {/* 投票模态框 */}
      <PollModal
        isOpen={showPollModal}
        onClose={() => setShowPollModal(false)}
        onCreatePoll={createPoll}
      />
    </div>
  );
};

export default GroupChat;
